package com.css.fxfzypg.modules.preAssessResult.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.css.fxfzypg.base.dict.repository.entity.DictItemEntity;
import com.css.fxfzypg.base.dict.service.DictService;
import com.css.fxfzypg.base.response.RestResponse;
import com.css.fxfzypg.constants.FxfzConstants;
import com.css.fxfzypg.modules.SettingSeismic.entity.SeismicIntensityRelation;
import com.css.fxfzypg.modules.SettingSeismic.entity.SettingSeismicDetails;
import com.css.fxfzypg.modules.SettingSeismic.entity.SettingSeismicPoint;
import com.css.fxfzypg.modules.SettingSeismic.repository.IntensityRelationRepository;
import com.css.fxfzypg.modules.SettingSeismic.repository.SettingSeismicRepository;
import com.css.fxfzypg.modules.SettingSeismic.service.SettingSeismicService;
import com.css.fxfzypg.modules.SettingSeismic.vo.SettingSeismicDetailsVO;
import com.css.fxfzypg.modules.baseData.entity.BuildingVulnerability;
import com.css.fxfzypg.modules.baseData.entity.HosPeoEntity;
import com.css.fxfzypg.modules.baseData.entity.PbeEntity;
import com.css.fxfzypg.modules.baseData.entity.VillageTownHosPeoEntity;
import com.css.fxfzypg.modules.baseData.repository.BuildingVulnerabilityRepository;
import com.css.fxfzypg.modules.baseData.repository.HosPeoRepository;
import com.css.fxfzypg.modules.baseData.service.BuildingVulnerabilityService;
import com.css.fxfzypg.modules.baseData.service.PbeService;
import com.css.fxfzypg.modules.baseData.service.VillageTownHosPeoService;
import com.css.fxfzypg.modules.earthquakedisasterloss.entity.SettingSeismicInfluenceflied;
import com.css.fxfzypg.modules.earthquakedisasterloss.repository.SettingSeismicInfluencefliedRepository;
import com.css.fxfzypg.modules.group.entity.GroupEntity;
import com.css.fxfzypg.modules.group.repository.GroupRepository;
import com.css.fxfzypg.modules.group.service.GroupService;
import com.css.fxfzypg.modules.group.service.GroupUserService;
import com.css.fxfzypg.modules.maps.service.SetEarthquakeMapService;
import com.css.fxfzypg.modules.maps.service.TaskRegionMapService;
import com.css.fxfzypg.modules.preAssessResult.entity.SeiCapDistribution;
import com.css.fxfzypg.modules.preAssessResult.repository.PreAssessResultRepository;
import com.css.fxfzypg.modules.preAssessResult.service.PreAssessResultService;
import com.css.fxfzypg.modules.preAssessResult.vo.*;
import com.css.fxfzypg.modules.preassesstaskmanage.entity.PreAssessTaskEntity;
import com.css.fxfzypg.modules.preassesstaskmanage.repository.PreAssessTaskRepository;
import com.css.fxfzypg.modules.preassesstaskmanage.vo.PreAssessVo;
import com.css.fxfzypg.modules.surveytaskmanage.vo.TaskVo;
import com.css.fxfzypg.util.*;
import com.css.fxfzypg.web.PlatformSessionContext;
import com.css.fxfzypg.zcpt.sys.entity.SUser;
import com.css.fxfzypg.zcpt.sys.service.SysRoleService;
import com.css.fxfzypg.zcpt.sys.service.impl.SUserServiceImpl;
import com.css.util.UuidUtil;
import org.geotools.data.FeatureWriter;
import org.geotools.data.shapefile.ShapefileDataStore;
import org.geotools.data.shapefile.ShapefileDataStoreFactory;
import org.geotools.feature.simple.SimpleFeatureTypeBuilder;
import org.geotools.referencing.CRS;
import org.locationtech.jts.geom.MultiPolygon;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;
import org.opengis.referencing.FactoryException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @author
 * @date 2022/10/13 17:01
 * @description
 **/
@Service
public class PreAssessResultImpl implements PreAssessResultService {
    @Autowired
    PreAssessResultRepository preAssessResultRepository;

    @Autowired
    PreAssessTaskRepository preAssessTaskRepository;

    @Autowired
    GroupRepository groupRepository;

    @Resource
    SettingSeismicRepository settingSeismicRepository;

    @Autowired
    SettingSeismicService settingSeismicService;

    @Resource
    SettingSeismicInfluencefliedRepository settingSeismicInfluencefliedRepository;

    @Autowired
    GroupUserService groupUserService;

    @Autowired
    GroupService groupService;

    @Autowired
    BuildingVulnerabilityRepository buildingVulnerabilityRepository;
    @Resource
    BuildingVulnerabilityService buildingVulnerabilityService;

    @Autowired
    PbeService pbeService;

    @Autowired
    HosPeoRepository hosPeoRepository;

    @Autowired
    SUserServiceImpl sUserServiceImpl;

    @Resource
    VillageTownHosPeoService villageTownHosPeoService;

    @Resource
    TaskRegionMapService taskRegionMapService;

    @Resource
    DictService dictService;

    @Resource
    RedisTemplate<String, String> redisTemplate;

    @Resource
    IntensityRelationRepository intensityRelationRepository;
    @Resource
    private SysRoleService roleService;

    public static final int BATCH_SIZE = 1000;

    @Value("${image.localDir}")
    private String localDir;
    @Override
    public Map<String, Object> taskPage(TaskVo taskVo, int curPage, int pageSize) {
        taskVo.setCreateUser(PlatformSessionContext.getUserID());
        Boolean flag = false;
        //Integer list = preAssessResultRepository.isTaskAdmin(taskVo.getCreateUser());
        //获取用户名称
        String sUser = sUserServiceImpl.getSUser(PlatformSessionContext.getUserID());
        SUser userInfo = CreateGson.createGson().fromJson(sUser, SUser.class);
        String userName = userInfo.getUserName();
        taskVo.setLoginName(userName);
        String roleByUserId = roleService.getRoleByUserId(PlatformSessionContext.getUserID());
        List<Map> roleMaps = JSONObject.parseArray(roleByUserId, Map.class);
        taskVo.setIsGjAdmin(false);
        for (Map roleMap : roleMaps) {
            String roleCode = (String) roleMap.get("roleCode");
            if (roleCode.equals(FxfzConstants.YPG_COUN_GL_ROLE)) {
                //是否是国家管理员 ，如果是国家管理员则不需要理会下面162和163行的这些条件
                taskVo.setIsGjAdmin(true);
            }
        }
        //父id为 0 的 与当前登录人有关（任务管理人、小组组长、小组组员、小组专家成员）的任务
        //子任务 已分配的与当前登录人有关
        Map<String, Object> parentTask = preAssessResultRepository.findParentIdByTask("0", taskVo, curPage, pageSize, flag);
        List<PreAssessVo> tasks = (List<PreAssessVo>) parentTask.get("rows");
        for (PreAssessVo task : tasks) {
            List<PreAssessVo> subTasks = getSubTasks(task.getId(), taskVo);
            if (subTasks.size() > 0 && subTasks != null) {
                task.setChildren(subTasks);
            }
        }
        return parentTask;
        /*if (list > 0) {
            Map<String, Object> parentTask = preAssessResultRepository.findParentIdByTask("0", taskVo, curPage, pageSize, flag);
            List<PreAssessVo> tasks = (List<PreAssessVo>) parentTask.get("rows");
            for (PreAssessVo task : tasks) {
                List<PreAssessVo> subTasks = getSubTasks(task.getId(), taskVo);
                task.setChildren(subTasks);
            }
            return parentTask;
        } else {
            flag = true;
            Map<String, Object> parentTask = preAssessResultRepository.findParentIdByTask("0", taskVo, curPage, pageSize, flag);
            List<PreAssessVo> tasks = (List<PreAssessVo>) parentTask.get("rows");
            for (PreAssessVo task : tasks) {
                List<PreAssessVo> subTasks = getSubTasks(task.getId(), taskVo);
                List<String> personnel = new ArrayList<>();
                for (PreAssessVo subTask : subTasks) {
                    if (PlatformObjectUtils.isNotEmpty(subTask.getGroupId())) {
                        GroupEntity groupEntity = groupRepository.selectGroup(subTask.getGroupId());
                        personnel.add(groupEntity.getGroupLeaderId());
                        List<GroupUserEntity> groupUserEntities = groupUserService.selectGroupMemberAndGroupExpert(subTask.getGroupId());
                        for (GroupUserEntity groupUserEntitie : groupUserEntities) {
                            personnel.add(groupUserEntitie.getUserId());
                        }
                        if (personnel.contains(PlatformSessionContext.getUserID())) {
                            task.setChildren(subTasks);
                        }
                    }
                }

            }
            return parentTask;
        }*/
    }

    private List<PreAssessVo> getSubTasks(String id, TaskVo taskVo) {
        List<PreAssessVo> tasks = preAssessResultRepository.findSubIdByTask(id, taskVo);
        if (tasks != null) {
            for (PreAssessVo task : tasks) {
                String id1 = task.getId();
                List<PreAssessVo> subTask = preAssessResultRepository.findSubIdByTask(id1, taskVo);
                task.setChildren(subTask);
            }
        }
        return tasks;
    }

    @Override
    public Map<String, Object> undistributedTaskPage(TaskVo taskVo, int curPage, int pageSize) {
        String sUser = sUserServiceImpl.getSUser(PlatformSessionContext.getUserID());
        SUser userInfo = CreateGson.createGson().fromJson(sUser, SUser.class);
        String userName = userInfo.getUserName();
        taskVo.setLoginName(userName);
        Map<String, Object> undistributedTask = preAssessResultRepository.undistributedTaskPage("0", taskVo, curPage, pageSize);
        List<PreAssessVo> tasks = (List<PreAssessVo>) undistributedTask.get("rows");
        for (PreAssessVo task : tasks) {
            List<PreAssessVo> subTasks = getSubTasks(task.getId(), taskVo);
            if (subTasks.size() > 0 && subTasks != null) {
                task.setChildren(subTasks);
            }
        }
        return undistributedTask;
    }


    @Override
    public PreAssessTaskInfoVo getPreAssessTaskInfo(String taskId) {
        PreAssessTaskEntity preAssessTaskEntity = preAssessTaskRepository.findById(taskId);

        PreAssessTaskInfoVo preAssessTaskInfoVo = new PreAssessTaskInfoVo();
        BeanUtils.copyProperties(preAssessTaskEntity, preAssessTaskInfoVo);
        if (PlatformObjectUtils.isNotEmpty(preAssessTaskEntity.getGroupId())) {
            GroupEntity groupEntity = groupRepository.selectGroup(preAssessTaskEntity.getGroupId());
            preAssessTaskInfoVo.setGroupMember(groupEntity.getGroupMember());
            if (PlatformObjectUtils.isNotEmpty(groupEntity.getGroupExpert())) {
                preAssessTaskInfoVo.setGroupExpert(groupEntity.getGroupExpert());
            }
        }


        //获取预评估人、预评估人所在单位、预评估日期
        List<SettingSeismicInfluenceflied> seismicInfluenceflieds = settingSeismicInfluencefliedRepository.findByTaskId(taskId);
        if (PlatformObjectUtils.isNotEmpty(seismicInfluenceflieds)) {
            for (int i = 0; i < seismicInfluenceflieds.size(); i++) {
                preAssessTaskInfoVo.setAssessmentTime(seismicInfluenceflieds.get(0).getAssessmentTime());
                preAssessTaskInfoVo.setAssessmentUserDept(seismicInfluenceflieds.get(0).getAssessmentUserDept());
                preAssessTaskInfoVo.setAssessmentUserId(seismicInfluenceflieds.get(0).getAssessmentUserId());
            }
        }
        return preAssessTaskInfoVo;
    }

    @Override
    public Boolean isHaveSetEarthquake(String taskId) {
        List<SettingSeismicDetails> settingSeismicDetails = settingSeismicService.getSettingSeismicDetailsByTaskId(taskId);
        if (PlatformObjectUtils.isNotEmpty(settingSeismicDetails)) {
            return true;
        }
        return false;
    }

    @Override
    public List<SettingSeismicDetailsVO> setEarthquakeCensus(String taskId) {
        String placeProvince = "";
        PreAssessTaskEntity preAssessTask = preAssessTaskRepository.findById(taskId);
        List<SettingSeismicDetailsVO> list = new ArrayList<>();

        //为子任务
        if (!"0".equals(preAssessTask.getParentId())) {
            String[] split = preAssessTask.getTaskDistrict().split("、");
            for (int i = 0; i < split.length; i++) {
                for (int l = 0; l < split[i].split("-").length; l++) {
                    placeProvince = split[i].split("-")[0];
                }
            }
            List<SettingSeismicDetailsVO> listVos = settingSeismicService.setEarthquakeCensus(taskId, placeProvince);
            list.addAll(listVos);
        } else {
            List<SettingSeismicDetailsVO> listVos = settingSeismicService.setEarthquakeCensus(taskId, placeProvince);
            list.addAll(listVos);
            List<PreAssessTaskEntity> subTask = preAssessTaskRepository.getSubTask(taskId);
            if (subTask != null && subTask.size() > 0) {
                for (PreAssessTaskEntity entity : subTask) {
                    String[] split = entity.getTaskDistrict().split("、");
                    for (int i = 0; i < split.length; i++) {
                        for (int l = 0; l < split[i].split("-").length; l++) {
                            placeProvince = split[i].split("-")[0];
                        }
                    }
                    List<SettingSeismicDetailsVO> lists = settingSeismicService.setEarthquakeCensus(entity.getId(), placeProvince);
                    list.addAll(lists);
                }
            }

        }
        for (SettingSeismicDetailsVO item : list) {
            item.setMacroPosition(item.getMacroPosition().replace(",", ""));
        }
        list.sort(Comparator.comparing(SettingSeismicDetailsVO::getFaultNum));
        return list;

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateEarthquakeCensus(String taskId) {
        List<SettingSeismicPoint> list = new ArrayList<>();
        PreAssessTaskEntity preAssessTask = preAssessTaskRepository.findById(taskId);
        //为子任务
        if (!"0".equals(preAssessTask.getParentId())) {
            list =settingSeismicService.getPointsByTaskId(preAssessTask.getId());
        }else {
            //为父任务，获取子任务
            List<PreAssessTaskEntity> subTask = preAssessTaskRepository.getSubTask(taskId);
            if (subTask != null && subTask.size() > 0) {
                for (PreAssessTaskEntity entity : subTask) {
                    List<SettingSeismicPoint> pointList =settingSeismicService.getPointsByTaskId(entity.getId());
                    list.addAll(pointList);
                }
            }
        }
        //更新 setting_seismic_point setting_seismic_details 的 faultNum
        for (int i = 0; i < list.size(); i++) {
            SettingSeismicPoint settingSeismicPoint = list.get(i);
            settingSeismicPoint.setFaultNum(i+1);
            int i1 = settingSeismicService.updateFaultNum(settingSeismicPoint);
        }
        return list.size();
    }

    @Resource
    SetEarthquakeMapService setEarthquakeMapService;

    @Override
    public RestResponse seiCapCalculationToAb(DistrictVO districtVO) {

      /*  preAssessResultRepository.delSeiCapCalByTaskId(taskId, type);
        SeismicIntensityRelation byTaskId = intensityRelationRepository.getByTaskId(taskId);
        if (PlatformObjectUtils.isEmpty(byTaskId)) {
            return RestResponse.fail(503, "请生成该任务下的地震影响场");
        }*/

        //比例
        BigDecimal highStructureTypeProp = null;
        BigDecimal steelStructureTypeProp = null;
        BigDecimal hntStructureTypeProp = null;
        BigDecimal zhStructureTypeProp = null;
        BigDecimal zmStructureTypeProp = null;
        BigDecimal sotlStructureTypeProp = null;
        BigDecimal woodStructureTypeProp = null;
        BigDecimal stoneStructureTypeProp = null;
        BigDecimal otherStructureTypeProp = null;

        //好轻中严毁
        BigDecimal basicallyIntact = null;
        BigDecimal minorDamage = null;
        BigDecimal moderateDamage = null;
        BigDecimal seriousDamage = null;
        BigDecimal damage = null;

        ////抗震能力指数
        List<DictItemEntity> itemList = dictService.getValidDictItemsByDictCode(FxfzConstants.KZNLZS);
        //好
        BigDecimal intact = BigDecimal.ONE;
        //轻
        BigDecimal slight = BigDecimal.valueOf(0.8);
        //中
        BigDecimal secondary = BigDecimal.valueOf(0.5);
        //严
        BigDecimal serious = BigDecimal.valueOf(0.3);
        //毁
        BigDecimal damage1 = BigDecimal.ZERO;
        for (DictItemEntity item : itemList) {
            String dictItemCode = item.getDictItemCode();
            if (PlatformObjectUtils.isEmpty(dictItemCode)) {
                continue;
            }
            switch (item.getDictItemName()) {
                case FxfzConstants.INTACT:
                    intact = new BigDecimal(dictItemCode);
                    break;
                case FxfzConstants.SLIGHT:
                    slight = new BigDecimal(dictItemCode);
                    break;
                case FxfzConstants.SECONDARY:
                    secondary = new BigDecimal(dictItemCode);
                    break;
                case FxfzConstants.SERIOUS:
                    serious = new BigDecimal(dictItemCode);
                    break;
                case FxfzConstants.DAMAGE:
                    damage1 = new BigDecimal(dictItemCode);
                    break;
            }
        }
        String taskDistrict = districtVO.getTaskDistrict();
        String province = "", city = "", county = "";
        String type="0";
        List<DistrictResultVO> vos=new ArrayList<>();

        switch (type) {
            case "2":
                List<BuildingVulnerability> allVulnerability = new ArrayList<>();
                break;
            default:
                List<AreaBoundaryVO> boundaryVOList = new ArrayList<>();
                String[] split = taskDistrict.split("、");
                if (PlatformObjectUtils.isNotEmpty(split)){
                    for (String s : split) {

                        if (PlatformObjectUtils.isNotEmpty(s)){
                            String[] split1 = s.split("-");
                            AreaBoundaryVO areaBoundaryVO = new AreaBoundaryVO();
                           if (s.contains("北京市")||s.contains("天津市")||s.contains("上海市")||s.contains("重庆市")){
                               String code = setEarthquakeMapService.getCodeByTaskDistrict(split1[0]+"-"+split1[2]);//230184结果为一个县级 code
                               String geom=buildingVulnerabilityService.getGeomByCode(code);
                                province=split1[0];
                                city=split1[0];
                                county=split1[2];
                                areaBoundaryVO.setGeomText(geom);

                            }else {
                               String code = setEarthquakeMapService.getCodeByTaskDistrict(s);//230184结果为一个县级 code
                               String geom=buildingVulnerabilityService.getGeomByCode(code);
                               province=split1[0];
                               city=split1[1];
                               county=split1[2];
                               areaBoundaryVO.setGeomText(geom);
                           }

                            areaBoundaryVO.setProvince(province);
                            areaBoundaryVO.setCity(city);
                            areaBoundaryVO.setCounty(county);
                            boundaryVOList.add(areaBoundaryVO);
                        }
                    }
                }

                if ("0".equals(type)) {
                    if (boundaryVOList == null || boundaryVOList.size() < 1) {
                        return RestResponse.fail(503, "未获取到所选区县信息！");
                    }
                }
                for (AreaBoundaryVO boundaryVO : boundaryVOList) {
                    province = boundaryVO.getProvince();
                    city = boundaryVO.getCity();
                    county = boundaryVO.getCounty();
                    StructuralProportionVO1 proportionVo = this.getStructuralProportion1(province, city, county,
                            null);
                    if (PlatformObjectUtils.isEmpty(proportionVo)) {
                        //tab1为true表示该格网在该任务区域内
                        boolean tab1 = false;
                        for (String s : taskDistrict.split("、")) {
                            if (s.equals(province + "-" + city + "-" + county)) {
                                tab1 = true;
                                break;
                            } else if (s.equals(province + "-" + city)) {
                                tab1 = true;
                                break;
                            } else if (s.equals(province)) {
                                tab1 = true;
                                break;
                            }
                        }
                        if (!tab1) {
                            continue;
                        }
                        return RestResponse.fail(503, "请先添加" + province + "-" + city + "-" + county + "的人口和建筑物概况（区县）的值！");
                    }
                    highStructureTypeProp = proportionVo.getDhpHighTatio();
                    steelStructureTypeProp = proportionVo.getDhpSteelTatio();
                    hntStructureTypeProp = proportionVo.getDhpBetonTatio();
                    zhStructureTypeProp = proportionVo.getDhpBrickTatio();
                    zmStructureTypeProp = proportionVo.getDhpMasonryTatio();
                    sotlStructureTypeProp = proportionVo.getDhpSoilTatio();
                    woodStructureTypeProp = proportionVo.getDhpWoodTatio();
                    stoneStructureTypeProp = proportionVo.getDhpStoneTatio();
                    otherStructureTypeProp = proportionVo.getDhpOtherTatio();


                    List<BuildingVulnerability> vulnerabilityList =
                            buildingVulnerabilityService.getAllVulnerabilityOrder(province, city, county, "2");
                    if (PlatformObjectUtils.isEmpty(vulnerabilityList)) {
                        //tab1为true表示该格网在该任务区域内
                        boolean tab1 = false;
                        for (String s : taskDistrict.split("、")) {
                            if (s.equals(province + "-" + city + "-" + county)) {
                                tab1 = true;
                                break;
                            } else if (s.equals(province + "-" + city)) {
                                tab1 = true;
                                break;
                            } else if (s.equals(province)) {
                                tab1 = true;
                                break;
                            }
                        }
                        if (!tab1) {
                            continue;
                        }
                        return RestResponse.fail(503, "未获取到" + province + "、" + city + "、" + county + "的建筑物易损性数据，请到【统计数据管理-建筑物易损性数据】菜单中维护！");
                    }
                    if (vulnerabilityList.size() % 5 != 0) {
                        return RestResponse.fail(503, province + "、" + city + "、" + county + "的建筑物易损性数据有异常！");
                    }

                        BigDecimal result = BigDecimal.ZERO;
                        //抗震能力值
                        BigDecimal highStructureType = null;
                        BigDecimal steelStructureType = null;
                        BigDecimal hntStructureType = null;
                        BigDecimal zhStructureType = null;
                        BigDecimal zmStructureType = null;
                        BigDecimal sotlStructureType = null;
                        BigDecimal woodStructureType = null;
                        BigDecimal stoneStructureType = null;
                        BigDecimal otherStructureType = null;
                        for (int a = 0; a < vulnerabilityList.size() / 5; a++) {
                            if (districtVO.getIntensity() == 6) {
                                basicallyIntact = vulnerabilityList.get(a * 5).getSix();
                                minorDamage = vulnerabilityList.get(a * 5 + 1).getSix();
                                moderateDamage = vulnerabilityList.get(a * 5 + 2).getSix();
                                seriousDamage = vulnerabilityList.get(a * 5 + 3).getSix();
                                damage = vulnerabilityList.get(a * 5 + 4).getSix();
                            } else if (districtVO.getIntensity() == 7) {
                                basicallyIntact = vulnerabilityList.get(a * 5).getSeven();
                                minorDamage = vulnerabilityList.get(a * 5 + 1).getSeven();
                                moderateDamage = vulnerabilityList.get(a * 5 + 2).getSeven();
                                seriousDamage = vulnerabilityList.get(a * 5 + 3).getSeven();
                                damage = vulnerabilityList.get(a * 5 + 4).getSeven();
                            } else if (districtVO.getIntensity() == 8) {
                                basicallyIntact = vulnerabilityList.get(a * 5).getEight();
                                minorDamage = vulnerabilityList.get(a * 5 + 1).getEight();
                                moderateDamage = vulnerabilityList.get(a * 5 + 2).getEight();
                                seriousDamage = vulnerabilityList.get(a * 5 + 3).getEight();
                                damage = vulnerabilityList.get(a * 5 + 4).getEight();
                            } else if (districtVO.getIntensity() == 9) {
                                basicallyIntact = vulnerabilityList.get(a * 5).getNine();
                                minorDamage = vulnerabilityList.get(a * 5 + 1).getNine();
                                moderateDamage = vulnerabilityList.get(a * 5 + 2).getNine();
                                seriousDamage = vulnerabilityList.get(a * 5 + 3).getNine();
                                damage = vulnerabilityList.get(a * 5 + 4).getNine();
                            } else if (districtVO.getIntensity() == 10) {
                                basicallyIntact = vulnerabilityList.get(a * 5).getTen();
                                minorDamage = vulnerabilityList.get(a * 5 + 1).getTen();
                                moderateDamage = vulnerabilityList.get(a * 5 + 2).getTen();
                                seriousDamage = vulnerabilityList.get(a * 5 + 3).getTen();
                                damage = vulnerabilityList.get(a * 5 + 4).getTen();
                            }
                            BigDecimal seiCapIndex = basicallyIntact.multiply(intact).add(minorDamage.multiply(slight))
                                    .add(moderateDamage.multiply(secondary)).add(seriousDamage.multiply(serious))
                                    .add(damage.multiply(damage1));
                            String structureType = vulnerabilityList.get(a * 5).getStructureType();
                            if (FxfzConstants.HIGH_STRUCTURE.equals(structureType)) {
                                highStructureType = seiCapIndex;
                                result = result.add(highStructureType.multiply(highStructureTypeProp));
                            } else if (FxfzConstants.STEEL_STRUCTURE.equals(structureType)) {
                                steelStructureType = seiCapIndex;
                                result = result.add(steelStructureType.multiply(steelStructureTypeProp));
                            } else if (FxfzConstants.HNT_STRUCTURE.equals(structureType)) {
                                hntStructureType = seiCapIndex;
                                result = result.add(hntStructureType.multiply(hntStructureTypeProp));
                            } else if (FxfzConstants.ZH_STRUCTURE.equals(structureType)) {
                                zhStructureType = seiCapIndex;
                                result = result.add(zhStructureType.multiply(zhStructureTypeProp));
                            } else if (FxfzConstants.ZM_STRUCTURE.equals(structureType)) {
                                zmStructureType = seiCapIndex;
                                result = result.add(zmStructureType.multiply(zmStructureTypeProp));
                            } else if (FxfzConstants.SOIL_STRUCTURE.equals(structureType)) {
                                sotlStructureType = seiCapIndex;
                                result = result.add(sotlStructureType.multiply(sotlStructureTypeProp));
                            } else if (FxfzConstants.WOOD_STRUCTURE.equals(structureType)) {
                                woodStructureType = seiCapIndex;
                                result = result.add(woodStructureType.multiply(woodStructureTypeProp));
                            } else if (FxfzConstants.STONE_STRUCTURE.equals(structureType)) {
                                stoneStructureType = seiCapIndex;
                                result = result.add(stoneStructureType.multiply(stoneStructureTypeProp));
                            } else if (FxfzConstants.OTHER_STRUCTURE.equals(structureType)) {
                                otherStructureType = seiCapIndex;
                                result = result.add(otherStructureType.multiply(otherStructureTypeProp));
                            }
                        }
                        DistrictResultVO vo=new DistrictResultVO();
                        vo.setProvince(province);
                        vo.setCity(city);
                        vo.setPrefecture(county);
                        vo.setResult(result.setScale(2, BigDecimal.ROUND_UP));
                        vo.setGeom(boundaryVO.getGeomText());
                        vo.setIntensity(districtVO.getIntensity());
                        vos.add(vo);
                    }
        }
        return RestResponse.succeed(vos);
    }

    @Override
    public List<SettingSeismicDetailsVO> setEarthquakeCensus(List<String> taskId) {
        List<String> placeProvince = new ArrayList<>();
        List<PreAssessTaskEntity> preAssessTaskList = preAssessTaskRepository.findById(taskId);
        if (PlatformObjectUtils.isNotEmpty(preAssessTaskList)) {
            for (PreAssessTaskEntity preAssessTask : preAssessTaskList) {
                if (!"0".equals(preAssessTask.getParentId())) {
                    String[] split = preAssessTask.getTaskDistrict().split("、");
                    for (int i = 0; i < split.length; i++) {
                        for (int l = 0; l < split[i].split("-").length; l++) {
                           String province = split[i].split("-")[0];
                           if(!placeProvince.contains(province)){
                               placeProvince.add(province);
                           }
                        }
                    }
                }
            }
        }
        List<SettingSeismicDetailsVO> list = settingSeismicService.setEarthquakeCensus(taskId, placeProvince);
        for (SettingSeismicDetailsVO item : list) {
            item.setMacroPosition(item.getMacroPosition().replace(",", ""));
        }
        return list;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void setEarthquakeDelete(String faultNum, String taskId) {
        String[] split = faultNum.split(",");
        int[] authorityIds = Arrays.stream(split).mapToInt(Integer::parseInt).toArray();
        Arrays.sort(authorityIds);
        for (int i = authorityIds.length - 1; i > -1; i--) {
            settingSeismicService.deleteByFaultNum(String.valueOf(authorityIds[i]), taskId);
        }
    }

    @Override
    public Map<String, Object> getDetailPage(SettingSeismicDetailsVO settingSeismicDetailsVO, int curPage, int pageSize) {
        Map<String, Object> page = settingSeismicService.getDetailPage(settingSeismicDetailsVO, curPage, pageSize);
        return page;
    }

    @Override
    public Map<String, Object> getDetailsPage(SettingSeismicDetailsVO settingSeismicDetailsVO, int curPage, int pageSize) {
        Map<String, Object> page = settingSeismicService.getDetailsPage(settingSeismicDetailsVO, curPage, pageSize);
        return page;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void detailDelete(String ids) {
        /*String[] split = ids.split(",");
        for (String id : split) {
            settingSeismicService.deleteById(id);
        }*/
        //zyt--批量删除details
        settingSeismicService.deleteById(ids);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void assignment(String taskId) {
        preAssessTaskRepository.assignment(taskId);
        List<PreAssessTaskEntity> subTasks = preAssessTaskRepository.getSubTask(taskId);
        for (PreAssessTaskEntity subTask : subTasks) {
            String provice = "";
            int index = subTask.getTaskDistrict().indexOf("-");
            if (index != -1) {
                provice = subTask.getTaskDistrict().substring(0, index);
            }
            //获取父任务taskId下 Provice 的 设定地震记录
            List<SettingSeismicDetailsVO> list = settingSeismicService.setEarthquakeCensus(taskId, provice);
            if (PlatformObjectUtils.isNotEmpty(list)) {
                for (SettingSeismicDetailsVO detailsVO : list) {
                    String ssId = detailsVO.getSsId();
                    SettingSeismicPoint settingSeismicPointById = settingSeismicRepository.getSettingSeismicPointById(ssId);
                    settingSeismicPointById.setSsId(UuidUtil.getUuid());
                    settingSeismicPointById.setTaskId(subTask.getId());
                    String[] split = settingSeismicPointById.getCoordinates().split(",");
                    String geom = "POINT(" + split[0] + " " + split[1] + ")";
                    settingSeismicPointById.setGeom(geom);
                    int i = settingSeismicRepository.saveSettingSeismicPoint(settingSeismicPointById);
                    if (i > 0) {
                        List<SettingSeismicDetails> detailsList = settingSeismicRepository.getSettingSeismicDetailsBySsId(ssId);
                        for (SettingSeismicDetails detail : detailsList) {
                            detail.setId(UUIDGenerator.getUUID());
                            detail.setSsId(settingSeismicPointById.getSsId());
                            settingSeismicRepository.saveSettingSeismicDetails(detail);
                        }
                    }
                }
            }
            preAssessTaskRepository.assignment(subTask.getId());
        }
    }

    private static List<String> getDiffrent(List<String> list1, List<String> list2) {
        List<String> diff = new ArrayList();
        for (String str : list1) {
            if (!list2.contains(str)) {
                diff.add(str);
            }
        }
        return diff;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RestResponse seiCapCalculation(String taskId, String type) {

        preAssessResultRepository.delSeiCapCalByTaskId(taskId, type);
        //这块存在问题  不知道什么情况 taskid查出来由存在多条数据的，现在是随机选择的第一条数据，但是不知道这样选择对不对，也不知道存在
        //多条数据到底合不合理
        SeismicIntensityRelation byTaskId = intensityRelationRepository.getByTaskId(taskId);
        if (PlatformObjectUtils.isEmpty(byTaskId)) {
            return RestResponse.fail(503, "请生成该任务下的地震影响场");
        }

        //比例
        BigDecimal highStructureTypeProp = null;
        BigDecimal steelStructureTypeProp = null;
        BigDecimal hntStructureTypeProp = null;
        BigDecimal zhStructureTypeProp = null;
        BigDecimal zmStructureTypeProp = null;
        BigDecimal sotlStructureTypeProp = null;
        BigDecimal woodStructureTypeProp = null;
        BigDecimal stoneStructureTypeProp = null;
        BigDecimal otherStructureTypeProp = null;

        //好轻中严毁
        BigDecimal basicallyIntact = null;
        BigDecimal minorDamage = null;
        BigDecimal moderateDamage = null;
        BigDecimal seriousDamage = null;
        BigDecimal damage = null;

        ////抗震能力指数
        List<DictItemEntity> itemList = dictService.getValidDictItemsByDictCode(FxfzConstants.KZNLZS);
        //好
        BigDecimal intact = BigDecimal.ONE;
        //轻
        BigDecimal slight = BigDecimal.valueOf(0.8);
        //中
        BigDecimal secondary = BigDecimal.valueOf(0.5);
        //严
        BigDecimal serious = BigDecimal.valueOf(0.3);
        //毁
        BigDecimal damage1 = BigDecimal.ZERO;
        for (DictItemEntity item : itemList) {
            String dictItemCode = item.getDictItemCode();
            if (PlatformObjectUtils.isEmpty(dictItemCode)) {
                continue;
            }
            switch (item.getDictItemName()) {
                case FxfzConstants.INTACT:
                    intact = new BigDecimal(dictItemCode);
                    break;
                case FxfzConstants.SLIGHT:
                    slight = new BigDecimal(dictItemCode);
                    break;
                case FxfzConstants.SECONDARY:
                    secondary = new BigDecimal(dictItemCode);
                    break;
                case FxfzConstants.SERIOUS:
                    serious = new BigDecimal(dictItemCode);
                    break;
                case FxfzConstants.DAMAGE:
                    damage1 = new BigDecimal(dictItemCode);
                    break;
            }
        }
        PreAssessTaskEntity byId = preAssessTaskRepository.findById(taskId);
        String taskDistrict = byId.getTaskDistrict();

        // List<Vulnerability> divisionList = preAssessResultRepository.getDistinckDivision(taskId);
        String province = "", city = "", county = "";
        switch (type) {
            case "2":
                List<BuildingVulnerability> allVulnerability = new ArrayList<>();

                byTaskId.setButton8_status3("1");
                List<PbeEntity> pbeEntityList = pbeService.getPbeInfo1(taskId);
                if (PlatformObjectUtils.isEmpty(pbeEntityList)) {
                    return RestResponse.fail(503, "未获取到该任务的格网信息！");
                }
                if (!"1".equals(pbeEntityList.get(0).getJglxType())) {
                    return RestResponse.fail(503, "请先维护人口建筑物经济格网中的建筑物结构占比后，重新点击计算！");
                }

                List<SeiCapDistribution> scdList = new ArrayList<>();
                for (PbeEntity pbeEntity : pbeEntityList) {
                    if (pbeEntity.getCoveredarea()==0||PlatformObjectUtils.isEmpty(pbeEntity.getCoveredarea())){
                        System.out.println(pbeEntity.getId()+"-------"+pbeEntity.getCoveredarea());
                        continue;
                    }
                    highStructureTypeProp = new BigDecimal(PlatformObjectUtils.isEmpty(pbeEntity.getJglxGcjz()) ? "0" : pbeEntity.getJglxGcjz()).divide(BigDecimal.valueOf(100), 10, BigDecimal.ROUND_UP);
                    steelStructureTypeProp = new BigDecimal(PlatformObjectUtils.isEmpty(pbeEntity.getJglxGjg()) ? "0" : pbeEntity.getJglxGjg()).divide(BigDecimal.valueOf(100), 10, BigDecimal.ROUND_UP);
                    hntStructureTypeProp = new BigDecimal(PlatformObjectUtils.isEmpty(pbeEntity.getJglxDcgjhntjg()) ? "0" : pbeEntity.getJglxDcgjhntjg()).divide(BigDecimal.valueOf(100), 10, BigDecimal.ROUND_UP);
                    zhStructureTypeProp = new BigDecimal(PlatformObjectUtils.isEmpty(pbeEntity.getJglxZhjg()) ? "0" : pbeEntity.getJglxZhjg()).divide(BigDecimal.valueOf(100), 10, BigDecimal.ROUND_UP);
                    zmStructureTypeProp = new BigDecimal(PlatformObjectUtils.isEmpty(pbeEntity.getJglxZmjg()) ? "0" : pbeEntity.getJglxZmjg()).divide(BigDecimal.valueOf(100), 10, BigDecimal.ROUND_UP);
                    sotlStructureTypeProp = new BigDecimal(PlatformObjectUtils.isEmpty(pbeEntity.getJglxTjg()) ? "0" : pbeEntity.getJglxTjg()).divide(BigDecimal.valueOf(100), 10, BigDecimal.ROUND_UP);
                    woodStructureTypeProp = new BigDecimal(PlatformObjectUtils.isEmpty(pbeEntity.getJglxMjg()) ? "0" : pbeEntity.getJglxMjg()).divide(BigDecimal.valueOf(100), 10, BigDecimal.ROUND_UP);
                    stoneStructureTypeProp = new BigDecimal(PlatformObjectUtils.isEmpty(pbeEntity.getJglxSjg()) ? "0" : pbeEntity.getJglxSjg()).divide(BigDecimal.valueOf(100), 10, BigDecimal.ROUND_UP);
                    otherStructureTypeProp = new BigDecimal(PlatformObjectUtils.isEmpty(pbeEntity.getJglxQtjg()) ? "0" : pbeEntity.getJglxQtjg()).divide(BigDecimal.valueOf(100), 10, BigDecimal.ROUND_UP);

                    //每个省市县只查询一次数据库
                    if (!pbeEntity.getProvince().equals(province) && !pbeEntity.getCity().equals(city) && !pbeEntity.getCounty().equals(county)) {
                        allVulnerability = buildingVulnerabilityService.getAllVulnerabilityOrder(pbeEntity.getProvince(),
                                pbeEntity.getCity(), pbeEntity.getCounty(), "2");
                    } else {
                        if (PlatformObjectUtils.isEmpty(allVulnerability)) {
                            allVulnerability = buildingVulnerabilityService.getAllVulnerabilityOrder(pbeEntity.getProvince(), pbeEntity.getCity(), pbeEntity.getCounty(), "2");
                        }
                    }
                    if (PlatformObjectUtils.isEmpty(allVulnerability)) {
                        return RestResponse.fail(503, "未获取到" + pbeEntity.getProvince() + "、" + pbeEntity.getCity() + "、" + pbeEntity.getCounty() + "的建筑物易损性数据，请到【统计数据管理-建筑物易损性数据】菜单中维护！");
                    }
                    if (allVulnerability.size() % 5 != 0) {
                        return RestResponse.fail(503, pbeEntity.getProvince() + "、" + pbeEntity.getCity() + "、" + pbeEntity.getCounty() + "的建筑物易损性数据有异常！");
                    }




                    //地震烈度，6~10
                    for (int j = 6; j <= 10; j++) {
                        BigDecimal result = BigDecimal.ZERO;
                        for (int a = 0; a < (allVulnerability.size() / 5); a++) {
                            //抗震能力值
                            BigDecimal highStructureType = null;
                            BigDecimal steelStructureType = null;
                            BigDecimal hntStructureType = null;
                            BigDecimal zhStructureType = null;
                            BigDecimal zmStructureType = null;
                            BigDecimal sotlStructureType = null;
                            BigDecimal woodStructureType = null;
                            BigDecimal stoneStructureType = null;
                            BigDecimal otherStructureType = null;
                            if (j == 6) {
                                basicallyIntact = allVulnerability.get(a * 5).getSix();
                                minorDamage = allVulnerability.get(a * 5 + 1).getSix();
                                moderateDamage = allVulnerability.get(a * 5 + 2).getSix();
                                seriousDamage = allVulnerability.get(a * 5 + 3).getSix();
                                damage = allVulnerability.get(a * 5 + 4).getSix();
                            } else if (j == 7) {
                                basicallyIntact = allVulnerability.get(a * 5).getSeven();
                                minorDamage = allVulnerability.get(a * 5 + 1).getSeven();
                                moderateDamage = allVulnerability.get(a * 5 + 2).getSeven();
                                seriousDamage = allVulnerability.get(a * 5 + 3).getSeven();
                                damage = allVulnerability.get(a * 5 + 4).getSeven();
                            } else if (j == 8) {
                                basicallyIntact = allVulnerability.get(a * 5).getEight();
                                minorDamage = allVulnerability.get(a * 5 + 1).getEight();
                                moderateDamage = allVulnerability.get(a * 5 + 2).getEight();
                                seriousDamage = allVulnerability.get(a * 5 + 3).getEight();
                                damage = allVulnerability.get(a * 5 + 4).getEight();
                            } else if (j == 9) {
                                basicallyIntact = allVulnerability.get(a * 5).getNine();
                                minorDamage = allVulnerability.get(a * 5 + 1).getNine();
                                moderateDamage = allVulnerability.get(a * 5 + 2).getNine();
                                seriousDamage = allVulnerability.get(a * 5 + 3).getNine();
                                damage = allVulnerability.get(a * 5 + 4).getNine();
                            } else if (j == 10) {
                                basicallyIntact = allVulnerability.get(a * 5).getTen();
                                minorDamage = allVulnerability.get(a * 5 + 1).getTen();
                                moderateDamage = allVulnerability.get(a * 5 + 2).getTen();
                                seriousDamage = allVulnerability.get(a * 5 + 3).getTen();
                                damage = allVulnerability.get(a * 5 + 4).getTen();
                            }
                            BigDecimal seiCapIndex = basicallyIntact.multiply(intact).add(minorDamage.multiply(slight))
                                    .add(moderateDamage.multiply(secondary)).add(seriousDamage.multiply(serious))
                                    .add(damage.multiply(damage1));
                            String structureType = allVulnerability.get(a * 5).getStructureType();
                            if (FxfzConstants.HIGH_STRUCTURE.equals(structureType)) {
                                highStructureType = seiCapIndex;
                                result = result.add(highStructureType.multiply(highStructureTypeProp));
                            } else if (FxfzConstants.STEEL_STRUCTURE.equals(structureType)) {
                                steelStructureType = seiCapIndex;
                                result = result.add(steelStructureType.multiply(steelStructureTypeProp));
                            } else if (FxfzConstants.HNT_STRUCTURE.equals(structureType)) {
                                hntStructureType = seiCapIndex;
                                result = result.add(hntStructureType.multiply(hntStructureTypeProp));
                            } else if (FxfzConstants.ZH_STRUCTURE.equals(structureType)) {
                                zhStructureType = seiCapIndex;
                                result = result.add(zhStructureType.multiply(zhStructureTypeProp));
                            } else if (FxfzConstants.ZM_STRUCTURE.equals(structureType)) {
                                zmStructureType = seiCapIndex;
                                result = result.add(zmStructureType.multiply(zmStructureTypeProp));
                            } else if (FxfzConstants.SOIL_STRUCTURE.equals(structureType)) {
                                sotlStructureType = seiCapIndex;
                                result = result.add(sotlStructureType.multiply(sotlStructureTypeProp));
                            } else if (FxfzConstants.WOOD_STRUCTURE.equals(structureType)) {
                                woodStructureType = seiCapIndex;
                                result = result.add(woodStructureType.multiply(woodStructureTypeProp));
                            } else if (FxfzConstants.STONE_STRUCTURE.equals(structureType)) {
                                stoneStructureType = seiCapIndex;
                                result = result.add(stoneStructureType.multiply(stoneStructureTypeProp));
                            } else if (FxfzConstants.OTHER_STRUCTURE.equals(structureType)) {
                                otherStructureType = seiCapIndex;
                                result = result.add(otherStructureType.multiply(otherStructureTypeProp));
                            }
                        }
                        SeiCapDistribution seiCapDistribution = new SeiCapDistribution();
                        seiCapDistribution.setId(UUIDGenerator.getUUID());
                        seiCapDistribution.setTaskId(taskId);
                        seiCapDistribution.setProvince(pbeEntity.getProvince());
                        seiCapDistribution.setCity(pbeEntity.getCity());
                        seiCapDistribution.setCounty(pbeEntity.getCounty());
                        seiCapDistribution.setSeismicCapacityValue(result.setScale(4, BigDecimal.ROUND_UP));
                        seiCapDistribution.setPbeId(pbeEntity.getPbeId());
                        seiCapDistribution.setDataSource(type);
                        seiCapDistribution.setGeom(pbeEntity.getGeomText());
                        seiCapDistribution.setDzIntensity(j + "");
                        scdList.add(seiCapDistribution);
                        //preAssessResultRepository.saveSeismicCapacity(seiCapDistribution);
                    }
                    province = pbeEntity.getProvince();
                    city = pbeEntity.getCity();
                    county = pbeEntity.getCounty();
                }
                if (scdList.size() > 0) {
                    System.out.println(scdList.size());
                    //一次1000条
                    int fromIndex = 0;
                    int toIndex = BATCH_SIZE;
                    while (fromIndex != scdList.size()) {
                        if (toIndex > scdList.size()) {
                            toIndex = scdList.size();
                        }
                        List<SeiCapDistribution> list = scdList.subList(fromIndex, toIndex);
                        int insertcount = preAssessResultRepository.saveScdList(list);
                        System.out.println("插入成功" + insertcount);
                        fromIndex = toIndex;
                        toIndex += BATCH_SIZE;
                        if (toIndex > scdList.size()) {
                            toIndex = scdList.size();
                        }
                    }
                }
                break;
            default:
                List<AreaBoundaryVO> boundaryVOList = new ArrayList<>();
                if ("0".equals(type)) {
                    boundaryVOList = preAssessResultRepository.getAreaBoundaryVO1(taskId);
                    if (boundaryVOList == null || boundaryVOList.size() < 1) {
                        return RestResponse.fail(503, "未获取到该任务的区县信息！");
                    }
                    byTaskId.setButton8_status1("1");
                } else if ("1".equals(type)) {
                    boundaryVOList = preAssessResultRepository.getAreaBoundaryVO2(taskId);
                    if (boundaryVOList == null || boundaryVOList.size() < 1) {
                        return RestResponse.fail(503, "未获取到该任务的乡镇信息！");
                    }
                    byTaskId.setButton8_status2("1");
                }
                for (AreaBoundaryVO boundaryVO : boundaryVOList) {
                    province = boundaryVO.getProvince();
                    city = boundaryVO.getCity();
                    county = boundaryVO.getCounty();
                    String town = boundaryVO.getStreet();//乡镇
                    if (!byId.getTaskDistrict().contains(province)) {
                        continue;
                    }
                    StructuralProportionVO1 proportionVo = this.getStructuralProportion1(province, city, county,
                            boundaryVO.getStreet());
                    if (PlatformObjectUtils.isEmpty(proportionVo)) {
                        //tab1为true表示该格网在该任务区域内
                        boolean tab1 = false;
                        for (String s : taskDistrict.split("、")) {
                            if (s.equals(province + "-" + city + "-" + county)) {
                                tab1 = true;
                                break;
                            } else if (s.equals(province + "-" + city)) {
                                tab1 = true;
                                break;
                            } else if (s.equals(province)) {
                                tab1 = true;
                                break;
                            }
                        }
                        if (!tab1) {
                            continue;
                        }
                        return RestResponse.fail(503, "请先添加" + province + "-" + city + "-" + county + "的人口和建筑物概况（区县）的值！");
                    }
                    highStructureTypeProp = proportionVo.getDhpHighTatio();
                    steelStructureTypeProp = proportionVo.getDhpSteelTatio();
                    hntStructureTypeProp = proportionVo.getDhpBetonTatio();
                    zhStructureTypeProp = proportionVo.getDhpBrickTatio();
                    zmStructureTypeProp = proportionVo.getDhpMasonryTatio();
                    sotlStructureTypeProp = proportionVo.getDhpSoilTatio();
                    woodStructureTypeProp = proportionVo.getDhpWoodTatio();
                    stoneStructureTypeProp = proportionVo.getDhpStoneTatio();
                    otherStructureTypeProp = proportionVo.getDhpOtherTatio();


                    List<BuildingVulnerability> vulnerabilityList =
                            buildingVulnerabilityService.getAllVulnerabilityOrder(province, city, county, "2");
                    if (PlatformObjectUtils.isEmpty(vulnerabilityList)) {
                        //tab1为true表示该格网在该任务区域内
                        boolean tab1 = false;
                        for (String s : taskDistrict.split("、")) {
                            if (s.equals(province + "-" + city + "-" + county)) {
                                tab1 = true;
                                break;
                            } else if (s.equals(province + "-" + city)) {
                                tab1 = true;
                                break;
                            } else if (s.equals(province)) {
                                tab1 = true;
                                break;
                            }
                        }
                        if (!tab1) {
                            continue;
                        }
                        return RestResponse.fail(503, "未获取到" + province + "、" + city + "、" + county + "的建筑物易损性数据，请到【统计数据管理-建筑物易损性数据】菜单中维护！");
                    }
                    if (vulnerabilityList.size() % 5 != 0) {
                        return RestResponse.fail(503, province + "、" + city + "、" + county + "的建筑物易损性数据有异常！");
                    }
                    //地震烈度，6~10
                    for (int j = 6; j <= 10; j++) {
                        BigDecimal result = BigDecimal.ZERO;
                        //抗震能力值
                        BigDecimal highStructureType = null;
                        BigDecimal steelStructureType = null;
                        BigDecimal hntStructureType = null;
                        BigDecimal zhStructureType = null;
                        BigDecimal zmStructureType = null;
                        BigDecimal sotlStructureType = null;
                        BigDecimal woodStructureType = null;
                        BigDecimal stoneStructureType = null;
                        BigDecimal otherStructureType = null;
                        for (int a = 0; a < vulnerabilityList.size() / 5; a++) {
                            if (j == 6) {
                                basicallyIntact = vulnerabilityList.get(a * 5).getSix();
                                minorDamage = vulnerabilityList.get(a * 5 + 1).getSix();
                                moderateDamage = vulnerabilityList.get(a * 5 + 2).getSix();
                                seriousDamage = vulnerabilityList.get(a * 5 + 3).getSix();
                                damage = vulnerabilityList.get(a * 5 + 4).getSix();
                            } else if (j == 7) {
                                basicallyIntact = vulnerabilityList.get(a * 5).getSeven();
                                minorDamage = vulnerabilityList.get(a * 5 + 1).getSeven();
                                moderateDamage = vulnerabilityList.get(a * 5 + 2).getSeven();
                                seriousDamage = vulnerabilityList.get(a * 5 + 3).getSeven();
                                damage = vulnerabilityList.get(a * 5 + 4).getSeven();
                            } else if (j == 8) {
                                basicallyIntact = vulnerabilityList.get(a * 5).getEight();
                                minorDamage = vulnerabilityList.get(a * 5 + 1).getEight();
                                moderateDamage = vulnerabilityList.get(a * 5 + 2).getEight();
                                seriousDamage = vulnerabilityList.get(a * 5 + 3).getEight();
                                damage = vulnerabilityList.get(a * 5 + 4).getEight();
                            } else if (j == 9) {
                                basicallyIntact = vulnerabilityList.get(a * 5).getNine();
                                minorDamage = vulnerabilityList.get(a * 5 + 1).getNine();
                                moderateDamage = vulnerabilityList.get(a * 5 + 2).getNine();
                                seriousDamage = vulnerabilityList.get(a * 5 + 3).getNine();
                                damage = vulnerabilityList.get(a * 5 + 4).getNine();
                            } else if (j == 10) {
                                basicallyIntact = vulnerabilityList.get(a * 5).getTen();
                                minorDamage = vulnerabilityList.get(a * 5 + 1).getTen();
                                moderateDamage = vulnerabilityList.get(a * 5 + 2).getTen();
                                seriousDamage = vulnerabilityList.get(a * 5 + 3).getTen();
                                damage = vulnerabilityList.get(a * 5 + 4).getTen();
                            }
                            BigDecimal seiCapIndex = basicallyIntact.multiply(intact).add(minorDamage.multiply(slight))
                                    .add(moderateDamage.multiply(secondary)).add(seriousDamage.multiply(serious))
                                    .add(damage.multiply(damage1));
                            String structureType = vulnerabilityList.get(a * 5).getStructureType();
                            if (FxfzConstants.HIGH_STRUCTURE.equals(structureType)) {
                                highStructureType = seiCapIndex;
                                result = result.add(highStructureType.multiply(highStructureTypeProp));
                            } else if (FxfzConstants.STEEL_STRUCTURE.equals(structureType)) {
                                steelStructureType = seiCapIndex;
                                result = result.add(steelStructureType.multiply(steelStructureTypeProp));
                            } else if (FxfzConstants.HNT_STRUCTURE.equals(structureType)) {
                                hntStructureType = seiCapIndex;
                                result = result.add(hntStructureType.multiply(hntStructureTypeProp));
                            } else if (FxfzConstants.ZH_STRUCTURE.equals(structureType)) {
                                zhStructureType = seiCapIndex;
                                result = result.add(zhStructureType.multiply(zhStructureTypeProp));
                            } else if (FxfzConstants.ZM_STRUCTURE.equals(structureType)) {
                                zmStructureType = seiCapIndex;
                                result = result.add(zmStructureType.multiply(zmStructureTypeProp));
                            } else if (FxfzConstants.SOIL_STRUCTURE.equals(structureType)) {
                                sotlStructureType = seiCapIndex;
                                result = result.add(sotlStructureType.multiply(sotlStructureTypeProp));
                            } else if (FxfzConstants.WOOD_STRUCTURE.equals(structureType)) {
                                woodStructureType = seiCapIndex;
                                result = result.add(woodStructureType.multiply(woodStructureTypeProp));
                            } else if (FxfzConstants.STONE_STRUCTURE.equals(structureType)) {
                                stoneStructureType = seiCapIndex;
                                result = result.add(stoneStructureType.multiply(stoneStructureTypeProp));
                            } else if (FxfzConstants.OTHER_STRUCTURE.equals(structureType)) {
                                otherStructureType = seiCapIndex;
                                result = result.add(otherStructureType.multiply(otherStructureTypeProp));
                            }
                        }
                        SeiCapDistribution seiCapDistribution = new SeiCapDistribution();
                        seiCapDistribution.setId(UUIDGenerator.getUUID());
                        seiCapDistribution.setTaskId(taskId);
                        seiCapDistribution.setProvince(province);
                        seiCapDistribution.setCity(city);
                        seiCapDistribution.setCounty(county);
                        seiCapDistribution.setTown(town);
                        seiCapDistribution.setSeismicCapacityValue(result.setScale(2, BigDecimal.ROUND_UP));
                        // seiCapDistribution.setPbeId(pbeEntity.getPbeId());
                        seiCapDistribution.setDataSource(type);
                        seiCapDistribution.setGeom(boundaryVO.getGeomText());
                        seiCapDistribution.setDzIntensity(j + "");
                        preAssessResultRepository.saveSeismicCapacity(seiCapDistribution);
                    }

                }
        }
        intensityRelationRepository.updateSeismicIntensityRelation(byTaskId);
        return RestResponse.succeed("建筑物抗震能力分布生成成功！");
    }

    // @Override
    // public void seiCapCalculation(String taskId) {
    //     List<SeiCapDistribution> seiCapCalculation = this.getSeiCapCalculation(taskId,"");
    //     if(seiCapCalculation.size()>0){
    //         preAssessResultRepository.delSeiCapCalByTaskId(taskId);
    //     }
    //     //比例
    //     BigDecimal highStructureTypeProp = null;
    //     BigDecimal steelStructureTypeProp = null;
    //     BigDecimal hntStructureTypeProp = null;
    //     BigDecimal zhStructureTypeProp = null;
    //     BigDecimal zmStructureTypeProp = null;
    //     BigDecimal sotlStructureTypeProp = null;
    //     BigDecimal woodStructureTypeProp = null;
    //     BigDecimal stoneStructureTypeProp = null;
    //     BigDecimal otherStructureTypeProp = null;
    //
    //     //好轻中严毁
    //     BigDecimal basicallyIntact  = null;
    //     BigDecimal minorDamage  = null;
    //     BigDecimal moderateDamage  = null;
    //     BigDecimal seriousDamage  = null;
    //     BigDecimal damage =  null;
    //
    //     SeiCapDistribution seiCapDistribution=new SeiCapDistribution();
    //
    //     List<Vulnerability> divisionList=preAssessResultRepository.getDistinckDivision(taskId);
    //
    //
    //     if(PlatformObjectUtils.isNotEmpty(divisionList)){
    //         for(Vulnerability item:divisionList){
    //
    //             String proCode=preAssessResultRepository.getprovinceCode(item.getProvince());
    //             if(PlatformObjectUtils.isNotEmpty(proCode)){
    //                 String citCode=preAssessResultRepository.getcityCode(item.getCity(),proCode.substring(0, 2));
    //                 if(PlatformObjectUtils.isNotEmpty(citCode)){
    //                     String countyCode=preAssessResultRepository.getcountyCode(item.getPrefecture(),citCode.substring(0, 4));
    //                     List<PbeEntity> pbeEntityList=pbeService.getPbeInfo(item.getPrefecture(),countyCode,taskId);
    //                     for(PbeEntity pbeEntity:pbeEntityList){
    //                         StructuralProportionVo structuralProportion = this.getStructuralProportion(pbeEntity);
    //                         /* HosPeoEntity hosPeoEntity = hosPeoRepository.findHosPeo(pbeEntity.getProvince(), pbeEntity.getCity(), pbeEntity.getCounty());*/
    //                         if("城镇".equals(structuralProportion.getTownorcontry())){
    //                             highStructureTypeProp = structuralProportion.getDhpTownHighTatio();
    //                             steelStructureTypeProp = structuralProportion.getDhpTownSteelTatio();
    //                             hntStructureTypeProp = structuralProportion.getDhpTownBetonTatio();
    //                             zhStructureTypeProp = structuralProportion.getDhpTownBrickTatio();
    //                             zmStructureTypeProp = structuralProportion.getDhpTownMasonryTatio();
    //                             sotlStructureTypeProp = structuralProportion.getDhpTownSoilTatio();
    //                             woodStructureTypeProp = structuralProportion.getDhpTownWoodTatio();
    //                             stoneStructureTypeProp = structuralProportion.getDhpTownStoneTatio();
    //                             otherStructureTypeProp = structuralProportion.getDhpTownOtherTatio();
    //                         }else{
    //                             highStructureTypeProp = structuralProportion.getDhpVillageHighTatio();
    //                             steelStructureTypeProp = structuralProportion.getDhpVillageSteelTatio();
    //                             hntStructureTypeProp = structuralProportion.getDhpVillageBetonTatio();
    //                             zhStructureTypeProp = structuralProportion.getDhpVillageBrickTatio();
    //                             zmStructureTypeProp = structuralProportion.getDhpVillageMasonryTatio();
    //                             sotlStructureTypeProp = structuralProportion.getDhpVillageSoilTatio();
    //                             woodStructureTypeProp = structuralProportion.getDhpVillageWoodTatio();
    //                             stoneStructureTypeProp = structuralProportion.getDhpVillageStoneTatio();
    //                             otherStructureTypeProp = structuralProportion.getDhpVillageOtherTatio();
    //                         }
    //
    //                         //地震烈度，6~10
    //                         for(int i=6;i<=10;i++){
    //                             List<Vulnerability> list = this.getMatrixGroupByStructureType(item.getProvince(),item.getCity(),item.getPrefecture(),taskId);
    //                             BigDecimal result = new BigDecimal(0.0);
    //                             for (int a = 0; a < list.size(); a++) {
    //                                 List<Vulnerability> vulnerabilityList = this.getMatrixByStructureType(item.getProvince(),item.getCity(),item.getPrefecture(),taskId,list.get(a).getStructureType());
    //                                 //抗震能力值
    //                                 BigDecimal highStructureType = null;
    //                                 BigDecimal steelStructureType = null;
    //                                 BigDecimal hntStructureType = null;
    //                                 BigDecimal zhStructureType = null;
    //                                 BigDecimal zmStructureType = null;
    //                                 BigDecimal sotlStructureType = null;
    //                                 BigDecimal woodStructureType = null;
    //                                 BigDecimal stoneStructureType = null;
    //                                 BigDecimal otherStructureType = null;
    //                                 for(int b=0;b<vulnerabilityList.size();b++){
    //                                     if(i==6){
    //                                         basicallyIntact = vulnerabilityList.get(0).getSix();
    //                                         minorDamage = vulnerabilityList.get(1).getSix();
    //                                         moderateDamage = vulnerabilityList.get(2).getSix();
    //                                         seriousDamage = vulnerabilityList.get(3).getSix();
    //                                         damage = vulnerabilityList.get(4).getSix();
    //                                     }else if(i==7){
    //                                         basicallyIntact = vulnerabilityList.get(0).getSeven();
    //                                         minorDamage = vulnerabilityList.get(1).getSeven();
    //                                         moderateDamage = vulnerabilityList.get(2).getSeven();
    //                                         seriousDamage = vulnerabilityList.get(3).getSeven();
    //                                         damage = vulnerabilityList.get(4).getSeven();
    //                                     }else if(i==8){
    //                                         basicallyIntact = vulnerabilityList.get(0).getEight();
    //                                         minorDamage = vulnerabilityList.get(1).getEight();
    //                                         moderateDamage = vulnerabilityList.get(2).getEight();
    //                                         seriousDamage = vulnerabilityList.get(3).getEight();
    //                                         damage = vulnerabilityList.get(4).getEight();
    //                                     }else if(i==9){
    //                                         basicallyIntact = vulnerabilityList.get(0).getNine();
    //                                         minorDamage = vulnerabilityList.get(1).getNine();
    //                                         moderateDamage = vulnerabilityList.get(2).getNine();
    //                                         seriousDamage = vulnerabilityList.get(3).getNine();
    //                                         damage = vulnerabilityList.get(4).getNine();
    //                                     }else if(i==10){
    //                                         basicallyIntact = vulnerabilityList.get(0).getTen();
    //                                         minorDamage = vulnerabilityList.get(1).getTen();
    //                                         moderateDamage = vulnerabilityList.get(2).getTen();
    //                                         seriousDamage = vulnerabilityList.get(3).getTen();
    //                                         damage = vulnerabilityList.get(4).getTen();
    //                                     }
    //                                 }
    //
    //
    //
    //                                 BigDecimal seiCapIndex = basicallyIntact.multiply(new BigDecimal(FxfzConstants.INTACT))
    //                                         .add(minorDamage.multiply(new BigDecimal(FxfzConstants.SLIGHT)))
    //                                         .add(moderateDamage.multiply(new BigDecimal(FxfzConstants.SECONDARY)))
    //                                         .add(seriousDamage.multiply(new BigDecimal(FxfzConstants.SERIOUS)))
    //                                         .add(damage.multiply(new BigDecimal(FxfzConstants.DAMAGE)));
    //                                 String structureType = list.get(a).getStructureType();
    //                                 if (FxfzConstants.HIGH_STRUCTURE.equals(structureType)) {
    //                                     highStructureType = seiCapIndex;
    //                                     result = result.add(highStructureType.multiply(highStructureTypeProp));
    //                                 } else if (FxfzConstants.STEEL_STRUCTURE.equals(structureType)) {
    //                                     steelStructureType = seiCapIndex;
    //                                     result = result.add(steelStructureType.multiply(steelStructureTypeProp));
    //                                 } else if (FxfzConstants.HNT_STRUCTURE.equals(structureType)) {
    //                                     hntStructureType = seiCapIndex;
    //                                     result = result.add(hntStructureType.multiply(hntStructureTypeProp));
    //                                 } else if (FxfzConstants.ZH_STRUCTURE.equals(structureType)) {
    //                                     zhStructureType = seiCapIndex;
    //                                     result = result.add(zhStructureType.multiply(zhStructureTypeProp));
    //                                 } else if (FxfzConstants.ZM_STRUCTURE.equals(structureType)) {
    //                                     zmStructureType = seiCapIndex;
    //                                     result = result.add(zmStructureType.multiply(zmStructureTypeProp));
    //                                 } else if (FxfzConstants.SOIL_STRUCTURE.equals(structureType)) {
    //                                     sotlStructureType = seiCapIndex;
    //                                     result = result.add(sotlStructureType.multiply(sotlStructureTypeProp));
    //                                 } else if (FxfzConstants.WOOD_STRUCTURE.equals(structureType)) {
    //                                     woodStructureType = seiCapIndex;
    //                                     result = result.add(woodStructureType.multiply(woodStructureTypeProp));
    //                                 } else if (FxfzConstants.STONE_STRUCTURE.equals(structureType)) {
    //                                     stoneStructureType = seiCapIndex;
    //                                     result = result.add(stoneStructureType.multiply(stoneStructureTypeProp));
    //                                 } else if (FxfzConstants.OTHER_STRUCTURE.equals(structureType)) {
    //                                     otherStructureType = seiCapIndex;
    //                                     result = result.add(otherStructureType.multiply(otherStructureTypeProp));
    //                                 }
    //                                 if (a == vulnerabilityList.size() - 1) {
    //                                     seiCapDistribution.setId(UUIDGenerator.getUUID());
    //                                     seiCapDistribution.setTaskId(taskId);
    //                                     seiCapDistribution.setProvince(vulnerabilityList.get(a).getProvince());
    //                                     seiCapDistribution.setCity(vulnerabilityList.get(a).getCity());
    //                                     seiCapDistribution.setCounty(vulnerabilityList.get(a).getPrefecture());
    //                                     seiCapDistribution.setSeismicCapacityValue(result.setScale(2, BigDecimal.ROUND_UP));
    //                                     seiCapDistribution.setPbeId(pbeEntity.getPbeId());
    //                                     seiCapDistribution.setGeom(pbeEntity.getGeomText());
    //                                     seiCapDistribution.setDz_intensity(i+"");
    //                                     preAssessResultRepository.saveSeismicCapacity(seiCapDistribution);
    //                                 }
    //                             }
    //                         }
    //
    //                         /*List<Vulnerability> vulnerabilityList = this.matrixSee(item.getProvince(),item.getCity(),item.getPrefecture(),taskId);
    //                         BigDecimal result = new BigDecimal(0.0);
    //                         for (int a = 0; a < vulnerabilityList.size(); a++) {
    //                             //抗震能力值
    //                             BigDecimal highStructureType = null;
    //                             BigDecimal steelStructureType = null;
    //                             BigDecimal hntStructureType = null;
    //                             BigDecimal zhStructureType = null;
    //                             BigDecimal zmStructureType = null;
    //                             BigDecimal sotlStructureType = null;
    //                             BigDecimal woodStructureType = null;
    //                             BigDecimal stoneStructureType = null;
    //                             BigDecimal otherStructureType = null;
    //
    //                             BigDecimal basicallyIntact = vulnerabilityList.get(a).getSix();
    //                             BigDecimal minorDamage = vulnerabilityList.get(a).getSeven();
    //                             BigDecimal moderateDamage = vulnerabilityList.get(a).getEight();
    //                             BigDecimal seriousDamage = vulnerabilityList.get(a).getNine();
    //                             BigDecimal damage = vulnerabilityList.get(a).getTen();
    //
    //                             BigDecimal seiCapIndex = basicallyIntact.multiply(new BigDecimal(FxfzConstants.INTACT))
    //                                     .add(minorDamage.multiply(new BigDecimal(FxfzConstants.SLIGHT)))
    //                                     .add(moderateDamage.multiply(new BigDecimal(FxfzConstants.SECONDARY)))
    //                                     .add(seriousDamage.multiply(new BigDecimal(FxfzConstants.SERIOUS)))
    //                                     .add(damage.multiply(new BigDecimal(FxfzConstants.DAMAGE)));
    //                             String structureType = vulnerabilityList.get(a).getStructureType();
    //                             if (FxfzConstants.HIGH_STRUCTURE.equals(structureType)) {
    //                                 highStructureType = seiCapIndex;
    //                                 result = result.add(highStructureType.multiply(highStructureTypeProp));
    //                             } else if (FxfzConstants.STEEL_STRUCTURE.equals(structureType)) {
    //                                 steelStructureType = seiCapIndex;
    //                                 result = result.add(steelStructureType.multiply(steelStructureTypeProp));
    //                             } else if (FxfzConstants.HNT_STRUCTURE.equals(structureType)) {
    //                                 hntStructureType = seiCapIndex;
    //                                 result = result.add(hntStructureType.multiply(hntStructureTypeProp));
    //                             } else if (FxfzConstants.ZH_STRUCTURE.equals(structureType)) {
    //                                 zhStructureType = seiCapIndex;
    //                                 result = result.add(zhStructureType.multiply(zhStructureTypeProp));
    //                             } else if (FxfzConstants.ZM_STRUCTURE.equals(structureType)) {
    //                                 zmStructureType = seiCapIndex;
    //                                 result = result.add(zmStructureType.multiply(zmStructureTypeProp));
    //                             } else if (FxfzConstants.SOIL_STRUCTURE.equals(structureType)) {
    //                                 sotlStructureType = seiCapIndex;
    //                                 result = result.add(sotlStructureType.multiply(sotlStructureTypeProp));
    //                             } else if (FxfzConstants.WOOD_STRUCTURE.equals(structureType)) {
    //                                 woodStructureType = seiCapIndex;
    //                                 result = result.add(woodStructureType.multiply(woodStructureTypeProp));
    //                             } else if (FxfzConstants.STONE_STRUCTURE.equals(structureType)) {
    //                                 stoneStructureType = seiCapIndex;
    //                                 result = result.add(stoneStructureType.multiply(stoneStructureTypeProp));
    //                             } else if (FxfzConstants.OTHER_STRUCTURE.equals(structureType)) {
    //                                 otherStructureType = seiCapIndex;
    //                                 result = result.add(otherStructureType.multiply(otherStructureTypeProp));
    //                             }
    //                             if (a == vulnerabilityList.size() - 1) {
    //                                 seiCapDistribution.setId(UUIDGenerator.getUUID());
    //                                 seiCapDistribution.setTaskId(taskId);
    //                                 seiCapDistribution.setProvince(vulnerabilityList.get(a).getProvince());
    //                                 seiCapDistribution.setCity(vulnerabilityList.get(a).getCity());
    //                                 seiCapDistribution.setCounty(vulnerabilityList.get(a).getPrefecture());
    //                                 seiCapDistribution.setSeismicCapacityValue(result.setScale(2, BigDecimal.ROUND_UP));
    //                                 seiCapDistribution.setPbeId(pbeEntity.getPbeId());
    //                                 seiCapDistribution.setGeom(pbeEntity.getGeomText());
    //                                 preAssessResultRepository.saveSeismicCapacity(seiCapDistribution);
    //                             }
    //                         }*/
    //                     }
    //                 }
    //             }
    //
    //         }
    //
    //     }
    //
    //
    // }

    @Override
    public StructuralProportionVo getStructuralProportion(String province, String city, String county, String town, String townorcontry) {
        StructuralProportionVo structuralProportionVo = new StructuralProportionVo();

        if ("".equals(town) || PlatformObjectUtils.isEmpty(town)) {
            //当格网里的乡镇为空时，查询县级的人口与建筑物信息
            HosPeoEntity hosPeoEntity = hosPeoRepository.findHosPeo(province, city, county);
            if (hosPeoEntity == null) {
                return null;
            }
            BeanUtils.copyProperties(hosPeoEntity, structuralProportionVo);
            if ("城镇".equals(townorcontry)) {
                structuralProportionVo.setDhpIndoorProperty(hosPeoEntity.getDhpTownIndoorProperty());
            } else {
                structuralProportionVo.setDhpIndoorProperty(hosPeoEntity.getDhpVillageIndoorProperty());
            }
        } else {
            //当格网里的乡镇不为空时，查询县级的人口与建筑物信息
            VillageTownHosPeoEntity hosPeoEntity = villageTownHosPeoService.findHosPeo(province, city, county, town);
            if (PlatformObjectUtils.isEmpty(hosPeoEntity)) {
                //当乡镇的人口与建筑物信息为空时，查询县级的人口与建筑物信息
                HosPeoEntity hosPeoEntity2 = hosPeoRepository.findHosPeo(province, city, county);
                if (hosPeoEntity2 == null) {
                    return null;
                }
                BeanUtils.copyProperties(hosPeoEntity2, structuralProportionVo);
                if ("城镇".equals(townorcontry)) {
                    structuralProportionVo.setDhpIndoorProperty(hosPeoEntity2.getDhpTownIndoorProperty());
                } else {
                    structuralProportionVo.setDhpIndoorProperty(hosPeoEntity2.getDhpVillageIndoorProperty());
                }
            } else {
                BeanUtils.copyProperties(hosPeoEntity, structuralProportionVo);
                if ("城镇".equals(townorcontry)) {
                    structuralProportionVo.setDhpIndoorProperty(hosPeoEntity.getDhpTownIndoorProperty());
                } else {
                    structuralProportionVo.setDhpIndoorProperty(hosPeoEntity.getDhpVillageIndoorProperty());
                }
            }
        }

        structuralProportionVo.setTownorcontry(townorcontry);
        if ("城镇".equals(structuralProportionVo.getTownorcontry())) {
            structuralProportionVo.setDhpTownHighTatio(structuralProportionVo.getDhpTownHighTatio().divide(new BigDecimal(100), 4, BigDecimal.ROUND_HALF_DOWN));
            structuralProportionVo.setDhpTownSteelTatio(structuralProportionVo.getDhpTownSteelTatio().divide(new BigDecimal(100), 4, BigDecimal.ROUND_HALF_DOWN));
            structuralProportionVo.setDhpTownBetonTatio(structuralProportionVo.getDhpTownBetonTatio().divide(new BigDecimal(100), 4, BigDecimal.ROUND_HALF_DOWN));
            structuralProportionVo.setDhpTownBrickTatio(structuralProportionVo.getDhpTownBrickTatio().divide(new BigDecimal(100), 4, BigDecimal.ROUND_HALF_DOWN));
            structuralProportionVo.setDhpTownMasonryTatio(structuralProportionVo.getDhpTownMasonryTatio().divide(new BigDecimal(100), 4, BigDecimal.ROUND_HALF_DOWN));
            structuralProportionVo.setDhpTownSoilTatio(structuralProportionVo.getDhpTownSoilTatio().divide(new BigDecimal(100), 4, BigDecimal.ROUND_HALF_DOWN));
            structuralProportionVo.setDhpTownWoodTatio(structuralProportionVo.getDhpTownWoodTatio().divide(new BigDecimal(100), 4, BigDecimal.ROUND_HALF_DOWN));
            structuralProportionVo.setDhpTownStoneTatio(structuralProportionVo.getDhpTownStoneTatio().divide(new BigDecimal(100), 4, BigDecimal.ROUND_HALF_DOWN));
            structuralProportionVo.setDhpTownOtherTatio(structuralProportionVo.getDhpTownOtherTatio().divide(new BigDecimal(100), 4, BigDecimal.ROUND_HALF_DOWN));
        } else {
            structuralProportionVo.setDhpVillageHighTatio(structuralProportionVo.getDhpVillageHighTatio().divide(new BigDecimal(100), 4, BigDecimal.ROUND_HALF_DOWN));
            structuralProportionVo.setDhpVillageSteelTatio(structuralProportionVo.getDhpVillageSteelTatio().divide(new BigDecimal(100), 4, BigDecimal.ROUND_HALF_DOWN));
            structuralProportionVo.setDhpVillageBetonTatio(structuralProportionVo.getDhpVillageBetonTatio().divide(new BigDecimal(100), 4, BigDecimal.ROUND_HALF_DOWN));
            structuralProportionVo.setDhpVillageBrickTatio(structuralProportionVo.getDhpVillageBrickTatio().divide(new BigDecimal(100), 4, BigDecimal.ROUND_HALF_DOWN));
            structuralProportionVo.setDhpVillageMasonryTatio(structuralProportionVo.getDhpVillageMasonryTatio().divide(new BigDecimal(100), 4, BigDecimal.ROUND_HALF_DOWN));
            structuralProportionVo.setDhpVillageSoilTatio(structuralProportionVo.getDhpVillageSoilTatio().divide(new BigDecimal(100), 4, BigDecimal.ROUND_HALF_DOWN));
            structuralProportionVo.setDhpVillageWoodTatio(structuralProportionVo.getDhpVillageWoodTatio().divide(new BigDecimal(100), 4, BigDecimal.ROUND_HALF_DOWN));
            structuralProportionVo.setDhpVillageStoneTatio(structuralProportionVo.getDhpVillageStoneTatio().divide(new BigDecimal(100), 4, BigDecimal.ROUND_HALF_DOWN));
            structuralProportionVo.setDhpVillageOtherTatio(structuralProportionVo.getDhpVillageOtherTatio().divide(new BigDecimal(100), 4, BigDecimal.ROUND_HALF_DOWN));
        }
        return structuralProportionVo;
    }

    // @Override
    public StructuralProportionVO1 getStructuralProportion1(String province, String city, String area, String street) {
        StructuralProportionVO1 structuralProportionVo = new StructuralProportionVO1();
        //高层占比=（城镇地区高层占比*城镇地区建筑占总体建筑物的比例/100+农村地区高层占比*（1-城镇地区建筑占总体建筑物的比例））/100
        if (PlatformObjectUtils.isEmpty(street)) {
            HosPeoEntity h = hosPeoRepository.findHosPeo(province, city, area);
            if (PlatformObjectUtils.isEmpty(h)) {
                return null;
            }
            BigDecimal townTatio = h.getDhpTownTatio();
            if (PlatformObjectUtils.isNotEmpty(townTatio)) {
                BigDecimal villageTatio = BigDecimal.valueOf(100).subtract(h.getDhpTownTatio());
                structuralProportionVo.setDhpHighTatio(h.getDhpTownHighTatio().multiply(townTatio).divide(new BigDecimal(10000), 4, BigDecimal.ROUND_HALF_DOWN).add(h.getDhpVillageHighTatio().multiply(villageTatio).divide(new BigDecimal(10000), 4, BigDecimal.ROUND_HALF_DOWN)));
                structuralProportionVo.setDhpSteelTatio(h.getDhpTownSteelTatio().multiply(townTatio).divide(new BigDecimal(10000), 4, BigDecimal.ROUND_HALF_DOWN).add(h.getDhpVillageSteelTatio().multiply(villageTatio).divide(new BigDecimal(10000), 4, BigDecimal.ROUND_HALF_DOWN)));
                structuralProportionVo.setDhpBetonTatio(h.getDhpTownBetonTatio().multiply(townTatio).divide(new BigDecimal(10000), 4, BigDecimal.ROUND_HALF_DOWN).add(h.getDhpVillageBetonTatio().multiply(villageTatio).divide(new BigDecimal(10000), 4, BigDecimal.ROUND_HALF_DOWN)));
                structuralProportionVo.setDhpBrickTatio(h.getDhpTownBrickTatio().multiply(townTatio).divide(new BigDecimal(10000), 4, BigDecimal.ROUND_HALF_DOWN).add(h.getDhpVillageBrickTatio().multiply(villageTatio).divide(new BigDecimal(10000), 4, BigDecimal.ROUND_HALF_DOWN)));
                structuralProportionVo.setDhpMasonryTatio(h.getDhpTownMasonryTatio().multiply(townTatio).divide(new BigDecimal(10000), 4, BigDecimal.ROUND_HALF_DOWN).add(h.getDhpVillageMasonryTatio().multiply(villageTatio).divide(new BigDecimal(10000), 4, BigDecimal.ROUND_HALF_DOWN)));
                structuralProportionVo.setDhpSoilTatio(h.getDhpTownSoilTatio().multiply(townTatio).divide(new BigDecimal(10000), 4, BigDecimal.ROUND_HALF_DOWN).add(h.getDhpVillageSoilTatio().multiply(villageTatio).divide(new BigDecimal(10000), 4, BigDecimal.ROUND_HALF_DOWN)));
                structuralProportionVo.setDhpWoodTatio(h.getDhpTownWoodTatio().multiply(townTatio).divide(new BigDecimal(10000), 4, BigDecimal.ROUND_HALF_DOWN).add(h.getDhpVillageWoodTatio().multiply(villageTatio).divide(new BigDecimal(10000), 4, BigDecimal.ROUND_HALF_DOWN)));
                structuralProportionVo.setDhpStoneTatio(h.getDhpTownStoneTatio().multiply(townTatio).divide(new BigDecimal(10000), 4, BigDecimal.ROUND_HALF_DOWN).add(h.getDhpVillageStoneTatio().multiply(villageTatio).divide(new BigDecimal(10000), 4, BigDecimal.ROUND_HALF_DOWN)));
                structuralProportionVo.setDhpOtherTatio(h.getDhpTownOtherTatio().multiply(townTatio).divide(new BigDecimal(10000), 4, BigDecimal.ROUND_HALF_DOWN).add(h.getDhpVillageOtherTatio().multiply(villageTatio).divide(new BigDecimal(10000), 4, BigDecimal.ROUND_HALF_DOWN)));
            }
        } else {
            VillageTownHosPeoEntity h1 = villageTownHosPeoService.findHosPeo(province, city, area, street);
            if (PlatformObjectUtils.isEmpty(h1)) {
                HosPeoEntity h2 = hosPeoRepository.findHosPeo(province, city, area);
                if (PlatformObjectUtils.isEmpty(h2)) {
                    return null;
                }
                BigDecimal townTatio = h2.getDhpTownTatio();
                if (PlatformObjectUtils.isNotEmpty(townTatio)) {
                    BigDecimal villageTatio = BigDecimal.valueOf(100).subtract(h2.getDhpTownTatio());
                    structuralProportionVo.setDhpHighTatio(h2.getDhpTownHighTatio().multiply(townTatio).divide(new BigDecimal(10000), 4, BigDecimal.ROUND_HALF_DOWN).add(h2.getDhpVillageHighTatio().multiply(villageTatio).divide(new BigDecimal(10000), 4, BigDecimal.ROUND_HALF_DOWN)));
                    structuralProportionVo.setDhpSteelTatio(h2.getDhpTownSteelTatio().multiply(townTatio).divide(new BigDecimal(10000), 4, BigDecimal.ROUND_HALF_DOWN).add(h2.getDhpVillageSteelTatio().multiply(villageTatio).divide(new BigDecimal(10000), 4, BigDecimal.ROUND_HALF_DOWN)));
                    structuralProportionVo.setDhpBetonTatio(h2.getDhpTownBetonTatio().multiply(townTatio).divide(new BigDecimal(10000), 4, BigDecimal.ROUND_HALF_DOWN).add(h2.getDhpVillageBetonTatio().multiply(villageTatio).divide(new BigDecimal(10000), 4, BigDecimal.ROUND_HALF_DOWN)));
                    structuralProportionVo.setDhpBrickTatio(h2.getDhpTownBrickTatio().multiply(townTatio).divide(new BigDecimal(10000), 4, BigDecimal.ROUND_HALF_DOWN).add(h2.getDhpVillageBrickTatio().multiply(villageTatio).divide(new BigDecimal(10000), 4, BigDecimal.ROUND_HALF_DOWN)));
                    structuralProportionVo.setDhpMasonryTatio(h2.getDhpTownMasonryTatio().multiply(townTatio).divide(new BigDecimal(10000), 4, BigDecimal.ROUND_HALF_DOWN).add(h2.getDhpVillageMasonryTatio().multiply(villageTatio).divide(new BigDecimal(10000), 4, BigDecimal.ROUND_HALF_DOWN)));
                    structuralProportionVo.setDhpSoilTatio(h2.getDhpTownSoilTatio().multiply(townTatio).divide(new BigDecimal(10000), 4, BigDecimal.ROUND_HALF_DOWN).add(h2.getDhpVillageSoilTatio().multiply(villageTatio).divide(new BigDecimal(10000), 4, BigDecimal.ROUND_HALF_DOWN)));
                    structuralProportionVo.setDhpWoodTatio(h2.getDhpTownWoodTatio().multiply(townTatio).divide(new BigDecimal(10000), 4, BigDecimal.ROUND_HALF_DOWN).add(h2.getDhpVillageWoodTatio().multiply(villageTatio).divide(new BigDecimal(10000), 4, BigDecimal.ROUND_HALF_DOWN)));
                    structuralProportionVo.setDhpStoneTatio(h2.getDhpTownStoneTatio().multiply(townTatio).divide(new BigDecimal(10000), 4, BigDecimal.ROUND_HALF_DOWN).add(h2.getDhpVillageStoneTatio().multiply(villageTatio).divide(new BigDecimal(10000), 4, BigDecimal.ROUND_HALF_DOWN)));
                    structuralProportionVo.setDhpOtherTatio(h2.getDhpTownOtherTatio().multiply(townTatio).divide(new BigDecimal(10000), 4, BigDecimal.ROUND_HALF_DOWN).add(h2.getDhpVillageOtherTatio().multiply(villageTatio).divide(new BigDecimal(10000), 4, BigDecimal.ROUND_HALF_DOWN)));

                }
            } else {
                BigDecimal townTatio = h1.getDhpTownTatio();
                BigDecimal villageTatio = BigDecimal.valueOf(100).subtract(h1.getDhpTownTatio());
                structuralProportionVo.setDhpHighTatio(h1.getDhpTownHighTatio().multiply(townTatio).divide(new BigDecimal(10000), 4, BigDecimal.ROUND_HALF_DOWN).add(h1.getDhpVillageHighTatio().multiply(villageTatio).divide(new BigDecimal(10000), 4, BigDecimal.ROUND_HALF_DOWN)));
                structuralProportionVo.setDhpSteelTatio(h1.getDhpTownSteelTatio().multiply(townTatio).divide(new BigDecimal(10000), 4, BigDecimal.ROUND_HALF_DOWN).add(h1.getDhpVillageSteelTatio().multiply(villageTatio).divide(new BigDecimal(10000), 4, BigDecimal.ROUND_HALF_DOWN)));
                structuralProportionVo.setDhpBetonTatio(h1.getDhpTownBetonTatio().multiply(townTatio).divide(new BigDecimal(10000), 4, BigDecimal.ROUND_HALF_DOWN).add(h1.getDhpVillageBetonTatio().multiply(villageTatio).divide(new BigDecimal(10000), 4, BigDecimal.ROUND_HALF_DOWN)));
                structuralProportionVo.setDhpBrickTatio(h1.getDhpTownBrickTatio().multiply(townTatio).divide(new BigDecimal(10000), 4, BigDecimal.ROUND_HALF_DOWN).add(h1.getDhpVillageBrickTatio().multiply(villageTatio).divide(new BigDecimal(10000), 4, BigDecimal.ROUND_HALF_DOWN)));
                structuralProportionVo.setDhpMasonryTatio(h1.getDhpTownMasonryTatio().multiply(townTatio).divide(new BigDecimal(10000), 4, BigDecimal.ROUND_HALF_DOWN).add(h1.getDhpVillageMasonryTatio().multiply(villageTatio).divide(new BigDecimal(10000), 4, BigDecimal.ROUND_HALF_DOWN)));
                structuralProportionVo.setDhpSoilTatio(h1.getDhpTownSoilTatio().multiply(townTatio).divide(new BigDecimal(10000), 4, BigDecimal.ROUND_HALF_DOWN).add(h1.getDhpVillageSoilTatio().multiply(villageTatio).divide(new BigDecimal(10000), 4, BigDecimal.ROUND_HALF_DOWN)));
                structuralProportionVo.setDhpWoodTatio(h1.getDhpTownWoodTatio().multiply(townTatio).divide(new BigDecimal(10000), 4, BigDecimal.ROUND_HALF_DOWN).add(h1.getDhpVillageWoodTatio().multiply(villageTatio).divide(new BigDecimal(10000), 4, BigDecimal.ROUND_HALF_DOWN)));
                structuralProportionVo.setDhpStoneTatio(h1.getDhpTownStoneTatio().multiply(townTatio).divide(new BigDecimal(10000), 4, BigDecimal.ROUND_HALF_DOWN).add(h1.getDhpVillageStoneTatio().multiply(villageTatio).divide(new BigDecimal(10000), 4, BigDecimal.ROUND_HALF_DOWN)));
                structuralProportionVo.setDhpOtherTatio(h1.getDhpTownOtherTatio().multiply(townTatio).divide(new BigDecimal(10000), 4, BigDecimal.ROUND_HALF_DOWN).add(h1.getDhpVillageOtherTatio().multiply(villageTatio).divide(new BigDecimal(10000), 4, BigDecimal.ROUND_HALF_DOWN)));
            }
        }
        return structuralProportionVo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteSeiCapdistribution(String taskId) {
        return preAssessResultRepository.deleteSeiCapdistribution(taskId);
    }


    @Override
    public List<SeiCapDistribution> getSeiCapCalculation(String taskId, String dzIntensity, String type) {
        List<SeiCapDistribution> list = preAssessResultRepository.getSeiCapCalculation(taskId, dzIntensity, type);
        return list;
    }

    @Override
    public SeiCapDistribution findByTaskIdLimit(String taskId, String type) {
        return preAssessResultRepository.findByTaskIdLimit(taskId, type);
    }

    /**
     * 结构
     *
     * @param type
     * @return
     */
    private String castType(String type) {
        if (FxfzConstants.HIGH_STRUCTURE.equals(type)) {
            type = "高层结构";
        }
        if (FxfzConstants.STEEL_STRUCTURE.equals(type)) {
            type = "钢结构";
        }
        if (FxfzConstants.HNT_STRUCTURE.equals(type)) {
            type = "多层钢筋混凝土结构";
        }
        if (FxfzConstants.ZH_STRUCTURE.equals(type)) {
            type = "砖混结构";
        }
        if (FxfzConstants.ZM_STRUCTURE.equals(type)) {
            type = "砖木结构";
        }
        if (FxfzConstants.SOIL_STRUCTURE.equals(type)) {
            type = "土结构";
        }
        if (FxfzConstants.WOOD_STRUCTURE.equals(type)) {
            type = "木结构";
        }
        if (FxfzConstants.STONE_STRUCTURE.equals(type)) {
            type = "石结构";
        }
        if (FxfzConstants.OTHER_STRUCTURE.equals(type)) {
            type = "其他结构";
        }
        return type;
    }

    @Override
    public void exportSeiCapCalculation(String taskId,String type,HttpServletResponse resp) throws Exception {
        List<SeiCapDistribution>  dataList =  preAssessResultRepository.getDataByTaskId(taskId,type);
        if(PlatformObjectUtils.isEmpty(dataList) || dataList.size()==0){
            throw new RuntimeException("导出失败，未查询到任何的抗震能力分布数据");
        }
        long postName = System.currentTimeMillis();
        buildData(dataList,postName);
        String zipPath = localDir +File.separator+ "抗震能力"+System.currentTimeMillis()+ ".zip";
        InputStream input = null;
        ZipOutputStream zipOut = null;

        File zipFile = new File(zipPath);
        try {
            zipOut = new ZipOutputStream(new FileOutputStream(zipFile));
            // zip的名称为
            zipOut.setComment("抗震能力");
            String[] shpFiles = new String[]{
                    localDir + File.separator  + "抗震能力"+postName+".dbf",
                    localDir + File.separator  + "抗震能力"+postName+".prj",
                    localDir + File.separator  + "抗震能力"+postName+".shp",
                    localDir + File.separator  + "抗震能力"+postName+".shx",
                    localDir + File.separator  + "抗震能力"+postName+".fix"
            };
            for (int i = 0; i < shpFiles.length; i++) {
                File file1 = new File(shpFiles[i]);
                input = new FileInputStream(file1);
                zipOut.putNextEntry(new ZipEntry(file1.getName()));
                int temp = 0;
                while ((temp = input.read()) != -1) {
                    zipOut.write(temp);
                }
            }
            for (String shpFile : shpFiles) {
                //删除生成的临时文件
                File file1 = new File(shpFile);
                file1.deleteOnExit();
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (input != null) {
                input.close();
            }
            if (zipOut != null) {
                zipOut.close();
            }
        }
        export(zipFile,resp);
    }

    private void export(File zipFile,HttpServletResponse response) throws IOException {
        InputStream fis = new BufferedInputStream(new FileInputStream(zipFile));
        byte[] buffer = new byte[fis.available()];
        fis.read(buffer);
        fis.close();
        response.reset();
        // 先去掉文件名称中的空格,然后转换编码格式为utf-8,保证不出现乱码,这个文件名称用于浏览器的下载框中自动显示的文件名
        response.setContentType("application/x-msdownload");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode(zipFile.getName(), "UTF-8"));
        response.setHeader("Access-Control-Allow-Origin","*");
        OutputStream os = new BufferedOutputStream(response.getOutputStream());
        os.write(buffer);// 输出文件
        os.flush();
        os.close();
    }
    //生成shp文件
    private void buildData(List<SeiCapDistribution>  dataList,long postName) throws Exception {
        String filePath = localDir+File.separator+"抗震能力" +postName+ ".shp";
        File file = new File(filePath);
        ShapefileDataStoreFactory sf = new ShapefileDataStoreFactory();
        ShapefileDataStore ds = (ShapefileDataStore) sf.createDataStore(file.toURI().toURL());
        ds.setCharset(Charset.forName("GBK"));
        SimpleFeatureTypeBuilder tb = new SimpleFeatureTypeBuilder();
        tb.setCRS(CRS.decode("EPSG:4490"));
        tb.setName("shapefile");
        tb.add("intensity", String.class);
        tb.add("value", BigDecimal.class);
        tb.add("the_geom", MultiPolygon.class);
        SimpleFeatureType simpleFeatureType = tb.buildFeatureType();
        ds.createSchema(simpleFeatureType);
        FeatureWriter featureWriter = ds.getFeatureWriter(ds.getTypeNames()[0], null);
        for (SeiCapDistribution seiCapDistribution : dataList) {
            SimpleFeature feature = (SimpleFeature) featureWriter.next();
            feature.setAttribute(1, seiCapDistribution.getDzIntensity());
            feature.setAttribute(2, seiCapDistribution.getSeismicCapacityValue());
            String geom =  seiCapDistribution.getGeomText();
            feature.setAttribute("the_geom", geom);
        }
        featureWriter.write();
        featureWriter.close();
        ds.dispose();
    }
}
